package com.qumitech.visualnovel.service.gift.impl;

import com.alibaba.fastjson.JSONObject;
import com.qumitech.visualnovel.component.exception.BusinessException;
import com.qumitech.visualnovel.component.util.ExcelUtils;
import com.qumitech.visualnovel.component.util.FileUtil;
import com.qumitech.visualnovel.component.util.HttpInvokeUtil;
import com.qumitech.visualnovel.component.util.TimeUtils;
import com.qumitech.visualnovel.model.common.BaseRsp;
import com.qumitech.visualnovel.model.common.ResultEnum;
import com.qumitech.visualnovel.model.common.UrlConstant;
import com.qumitech.visualnovel.pubdef.dto.gift.*;
import com.qumitech.visualnovel.service.gift.GiftService;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author :  ZhChNing
 * @Descriptiom :
 * @Date Created in 2019/9/18 14:04
 */
@Service
public class GiftServiceImpl implements GiftService {
    private final String receiveDetailUrl = "/gift/console/receive/detail";

    private final String receivelistUrl = "/gift/console/receive/list";

    private final String configListUrl = "/gift/console/config/list";
    private final String statisticsListUrl = "/gift/console/statistics";

    private static final  String GIFT_GET_PRIORITY = "/gift/console/priority";
    private static final  String GIFT_PUT_PRIORITY = "/gift/console/priority";

    @Override
    public Map<String, Object> listGiftDetailAdminDTO(UserGiftDetailAdminQueryDTO queryDTO) {
        return listGiftDto(queryDTO, receiveDetailUrl);
    }

    private Map<String, Object> listGiftDto(UserGiftDetailAdminQueryDTO queryDTO, String restUrl){
        String url = UrlConstant.SERVER_URL + restUrl;
        Map<String, String> paramMap = new HashMap<>();
        if (queryDTO.getOffset() != null)
            paramMap.put("offset", queryDTO.getOffset().toString());
        if (queryDTO.getLimit() != null)
            paramMap.put("limit", queryDTO.getLimit().toString());
        if (queryDTO.getStartTime() != null)
            paramMap.put("startTime", queryDTO.getStartTime());
        if (queryDTO.getEndTime() != null)
            paramMap.put("endTime", queryDTO.getEndTime());
        if (queryDTO.getCostType() != null)
            paramMap.put("cost_type", queryDTO.getCostType().toString());
        if (queryDTO.getFromUid() != null)
            paramMap.put("from_uid", queryDTO.getFromUid().toString());
        if (queryDTO.getToUid() != null)
            paramMap.put("to_uid", queryDTO.getToUid().toString());
        if (queryDTO.getAnchorId() != null)
            paramMap.put("auchor_id", queryDTO.getAnchorId().toString());
        if (queryDTO.getGiftOriginFromType() != null)
            paramMap.put("gift_origin_from_type", queryDTO.getGiftOriginFromType());

        String body = HttpInvokeUtil.httpGet(url, paramMap, null);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        if (rsp == null || rsp.getStatus() != ResultEnum.SUCCESS.getState()
                || rsp.getData() == null) {
            throw new BusinessException(ResultEnum.FAILURE);
        }
        Map<String, Object> rspMap = (Map<String, Object>) rsp.getData();
        return rspMap;
    }

    @Override
    public Map<String, Object> exportMultipartFile(UserGiftDetailAdminQueryDTO queryDTO, HttpServletResponse request) {
        Map<String, Object> rspMap = listGiftDto(queryDTO, receivelistUrl);
        UserGiftImportDTO importDTO = JSONObject.parseObject(JSONObject.toJSONString(rspMap), UserGiftImportDTO.class);
        Map<String, Object> resultMap = new HashMap<>();
        try {
            List<UserGiftDetailAdminDTO> detailAdminDTOS = importDTO.getGiftDetailAdminDTOList();
            detailAdminDTOS.stream().forEach(withdrawApplyAdminDTO -> {
                withdrawApplyAdminDTO.setCostTypeN("钻石");
                if (withdrawApplyAdminDTO.getCostType().intValue() == 1) {
                    withdrawApplyAdminDTO.setCostTypeN("金豆");
                }
                withdrawApplyAdminDTO.setCreateTimeS(TimeUtils.getTime(withdrawApplyAdminDTO.getCreateTime()));

            });


            ExcelUtils<UserGiftDetailAdminDTO> xls = new ExcelUtils<UserGiftDetailAdminDTO>(UserGiftDetailAdminDTO.class);
            String filename = FileUtil.getExcelName();
            request.reset();
            request.setContentType("application/vnd.ms-excel;charset=utf-8");

            request.setHeader("Content-Disposition", "attachment;filename=" + filename);
            OutputStream outputStream = request.getOutputStream();
            xls.exportExcel("用户送礼明细导出", detailAdminDTOS, outputStream);
            outputStream.flush();
            outputStream.close();
            resultMap.put("title", filename);
            return resultMap;
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        throw new BusinessException(ResultEnum.EXCEL_EXPORT_ERROR);
    }

    @Override
    public Map<String, Object> listGiftBaseConfig() {
        String url = UrlConstant.SERVER_URL + configListUrl;
        String body = HttpInvokeUtil.httpGet(url, null, null);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        Map<String, Object> rspMap = (Map<String, Object>) rsp.getData();
        return rspMap;
    }

    @Override
    public BaseRsp getStatistics(UserGiftPresentStatisticsAdminQueryDTO queryAdminDTO) {
        String url = UrlConstant.SERVER_URL + statisticsListUrl;
        JSONObject o = JSONObject.parseObject(JSONObject.toJSONString(queryAdminDTO));
        Map<String, Object> req = JSONObject.toJavaObject(o, Map.class);
        String body = HttpInvokeUtil.httpGet(url, req);
        return JSONObject.parseObject(body, BaseRsp.class);
    }

    @Override
    public BaseRsp getGiftPriority() {
        String url = UrlConstant.SERVER_URL + GIFT_GET_PRIORITY;
        String body = HttpInvokeUtil.httpGet(url, new HashMap<>());
        return JSONObject.parseObject(body, BaseRsp.class);
    }

    @Override
    public BaseRsp editGiftPriority(List<GiftBaseConfigSortedDTO> sortedDTOS) {
        String url = UrlConstant.SERVER_URL + GIFT_PUT_PRIORITY;
        String req = JSONObject.toJSONString(sortedDTOS);
        String body = HttpInvokeUtil.httpPutJson(url,req,UrlConstant.DefaultEncode,null);
        return JSONObject.parseObject(body, BaseRsp.class);
    }
}
